<!doctype html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>

        <style>
            * {
                padding: 0;
                margin: 0;
            }

            .container {
                width: 200px;
                height: 600px;

                margin: 0 auto;
            }

            .box1 {
                width: 200px;
                height: 190px;
                background-color: aqua;
                border: 2px solid black;
            }

            .box2 {
                width: 200px;
                height: 190px;
                border: 2px solid black;
            }

            .box3 {
                width: 200px;
                height: 190px;
                border: 2px solid black;
            }
        </style>
    </head>

    <body>
        <div class="container">
            <div class="box1" draggable="true"><span>1</span></div>
            <div class="box1" draggable="true"><span>2</span></div>
            <div class="box1" draggable="true"><span>3</span></div>
        </div>

        <script>
            let container = document.querySelector('.container');
            let box1s = document.querySelectorAll('.box1');

            let box1sArray = Array.from(box1s);

            box1s.forEach((box1, index) => {
                box1.addEventListener('dragstart', (e) => {
                    e.dataTransfer.setData('text/plain', index);
                });
            });

            container.addEventListener('dragover', (e) => {
                e.preventDefault();
            });

            container.addEventListener('drop', (e) => {
                e.stopPropagation();

                if (e.dataTransfer.getData('text/plain')) {
                    let sourceIndex = e.dataTransfer.getData('text/plain');
                    let targetIndex = Array.from(box1s).indexOf(e.target);

                    [box1sArray[sourceIndex], box1sArray[targetIndex]] = [
                        box1sArray[targetIndex],
                        box1sArray[sourceIndex],
                    ];

                    box1sArray.forEach((box1, index) => {
                        container.appendChild(box1);
                    });
                }
            });
        </script>
    </body>
</html>
